package cn.tedu.vrd.filter;

import cn.tedu.vrd.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",urlPatterns = {"/send.html","/admin.html","/admin-banner.html","/admin-product.html"})
public class MyFilter implements Filter {
//    销毁时执行的方法
    public void destroy() {
    }
//当拦截到请求时执行的方法
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request=(HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse)resp;
//        通过请求对象得到会话对象
        HttpSession session=request.getSession();
//        得到会话对象中的user对象
        User user=(User) session.getAttribute("user");
        //        判断是否登录过
        if (user!=null){/*登录过*/
            chain.doFilter(req, resp);/*放行*/
        }else {/*没登录过*/
            /*重定向到登录页面*/
            response.sendRedirect("/login.html");
        }


    }
//初始化时执行的方法
    public void init(FilterConfig config) throws ServletException {

    }

}
